package com.china.produce.controller;

import com.china.produce.pojo.OrderMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description 发送消息
 * @CreateTime 2025/7/22
 */
@Slf4j
@RestController
@RequestMapping("/msg")
@RequiredArgsConstructor
public class MessageController {


    private final RocketMQTemplate rocketMQTemplate;

    @GetMapping("/send/{msg}")
    public String sendMessage(@PathVariable("msg") String msg) {

        log.info("发送消息 ：" + msg);

        rocketMQTemplate.convertAndSend("test-topic", msg);

        return "消息发送成功: " + msg;
    }

    @GetMapping("/sendTxMsg/{orderId}")
    public void sendTxMsg(@PathVariable("orderId") String orderId) {
        Message<String> message = MessageBuilder.withPayload("创建订单: " + orderId)
                .setHeader(RocketMQHeaders.TRANSACTION_ID, orderId)
                .build();

        rocketMQTemplate.sendMessageInTransaction(
                "tx_topic", //topic
                message,
                orderId // arg，用于本地事务执行时的业务参数
        );
    }

    @GetMapping("/sendOrderMsg/{orderId}")
    public void sendOrderMsg(@PathVariable("orderId") String orderId) {

        for (int i = 0; i < 5; i++) {
            OrderMessage message = new OrderMessage("order_topic", "创建订单: " + orderId + " i " + i);
            rocketMQTemplate.syncSendOrderly("order_topic", MessageBuilder.withPayload(message).build(), orderId);
        }

    }
}
